import { StorageProps, StorageUtils } from '../type/storage';


export default class StorageService<T = string> implements StorageUtils {
    /** 缓存对象key名称 */
    private storageKey: string = '';
    /** 缓存类型 local还是session */
    private type: string = '';
    constructor(props: StorageProps) {
        const { storageKey, type = 'local' } = props;
        this.storageKey = storageKey;
        this.type = type;
        if (type === 'local') {
            const localStore = window.localStorage.getItem(this.storageKey) || '{}'
            window.localStorage.setItem(this.storageKey, localStore)
        } else {
            const sessionStore = window.localStorage.getItem(this.storageKey) || '{}'
            window.sessionStorage.setItem(this.storageKey, sessionStore)
        }
    }
    private getStorage() {
        return (this.type === 'local' ? JSON.parse(window.localStorage.getItem(this.storageKey) || '{}') : JSON.parse(window.sessionStorage.getItem(this.storageKey) || '{}'));
    }
    private setStorage(storage: any) {
        if (this.type === 'local') {
            window.localStorage.setItem(this.storageKey, JSON.stringify(storage))
        } else {
            window.sessionStorage.setItem(this.storageKey, JSON.stringify(storage))
        }
    }
    /** 根据key获取值 */
    get(key: T) {
        const storage = this.getStorage();
        return storage[key]
    }
    /** 根据key设置值 */
    set(key: T, value: any) {
        const storage = this.getStorage();
        storage[key] = value;
        this.setStorage(storage)
    }
    /** 根据key删除缓存对象里某个key-value */
    remove(key: T) {
        const storage = this.getStorage();
        const removeStatus = delete storage[key];
        if (removeStatus) {
            this.setStorage(storage)
        }
    }
    /** 清除缓存 */
    clear() {
        this.setStorage({})
    }
}

